<template>
  <a-drawer
    title="新建角色"
    :width="550"
    :visible="visible"
    :body-style="{ paddingBottom: '80px' }"
    :closable="false"
    @close="onClose"
  >
    <a-form :form="form" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item style="display:none">
            <a-input v-decorator="['id']"/>
          </a-form-item>
          <a-form-item label="角色唯一标示">
            <a-input
              v-decorator="['roleCode',{rules: [{ required: true, message: '请输入角色标示', pattern: /^[^\s]*$/ }],},]"
              placeholder="请输入角色编码"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="角色名称">
            <a-input
              v-decorator="['roleName',{rules: [{ required: true, message: '请输入角色名称', pattern: /^[^\s]*$/ }],},]"
              placeholder="请输入角色名称"
            >
            </a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="状态">
            <a-select
              v-decorator="['status',{rules: [{ required: true, message: '请选择状态'}],}]"
              placeholder="请选择状态"
            >
              <a-select-option value="true">
                正常
              </a-select-option>
              <a-select-option value="false">
                禁用
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="排序号">
            <a-input-number
              :min="0"
              :max="100"
              v-decorator="['roleSort']"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="数据权限范围">
            <a-select
              v-decorator="['dataScope',{rules: [{ required: true, message: '请选择数据权限标示' }],},]"
              placeholder="请选择数据权限"
              @change="onDataScopeChange"
            >
              <a-select-option value="1">全部数据权限</a-select-option>
              <a-select-option value="2">自定义数据权限</a-select-option>
              <a-select-option value="3">本部门数据权限</a-select-option>
              <a-select-option value="4">本部门及以下数据权限</a-select-option>
              <a-select-option value="5">仅本人数据权限</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="描述">
            <a-textarea
              v-decorator="['remark']"
              :rows="4"
              placeholder="在这里输入角色描述..."></a-textarea>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16" v-if="permissionVisible">
        <a-divider>自定义权限</a-divider>
        <a-col :span="24">
          <a-form-item>
            <a-tree
              v-model="checkedKeys"
              checkable
              :auto-expand-parent="false"
              :defaultExpandAll="true"
              :selected-keys="selectedKeys"
              :replaceFields="replaceFields"
              :tree-data="treeData"
              @check="onCheck"
              @select="onSelect"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-popconfirm title="真的放弃编辑吗?" @confirm="onClose">
        <a-button :style="{ marginRight: '8px' }">
          取消
        </a-button>
      </a-popconfirm>
      <a-button type="primary" @click="roleSubmit">
        保存
      </a-button>
    </div>
  </a-drawer>
</template>
<script>
  import { findAllDeptTree, addRole, roleDetails, editRole } from '@/api/system'
  import pick from 'lodash.pick'
  import { getParentId } from '@/utils/util'

  export default {
    name: 'RoleModal',
    data () {
      return {
        replaceFields: {
          children: 'children',
          title: 'name',
          key: 'id'
        },
        form: this.$form.createForm(this),
        visible: false,
        mdl: {},
        disabled: false,
        treeData: [],
        selectedKeys: [],
        checkedKeys: [],
        permissionVisible: false,
        halfCheckedKeys: [],
        treeCheck: false,
        pidSet: [],
        submitFlag: null
      }
    },
    created () {
      this.loadDept()
    },
    watch: {
    },
    methods: {
      onCheck (checkedKeys, info) {
        if (!this.treeCheck) this.treeCheck = true
        this.checkedKeys = checkedKeys
        this.halfCheckedKeys = info.halfCheckedKeys
      },
      onSelect (selectedKeys) {
        this.selectedKeys = selectedKeys
      },
      onDataScopeChange (value) {
        this.permissionVisible = value === '2'
      },
      loadDept () {
        return new Promise(resolve => {
          findAllDeptTree().then(res => {
            this.treeData = res.data
            resolve(res.data)
          })
        })
      },
      add () {
        this.submitFlag = 'save'
        this.form.resetFields()
        this.mdl = {}
        this.visible = true
        this.permissionVisible = false
        this.pidSet = []
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.mdl, 'roleSort', 'roleCode', 'roleName', 'dataScope', 'status', 'remark', 'checkedKeys'))
        })
      },
      async edit (record) {
        this.permissionVisible = false
        await this.loadDept()
        if (record.id > 0) {
            roleDetails({ id: record.id }).then(res => {
            this.submitFlag = 'edit'
            const arr = []
            if (res.data.dataScope === '2') {
              const pids = getParentId(this.treeData, arr)
              const pidSet = new Set(pids.map(m => m + ''))
              const checkedLists = Array.from(pidSet)
              this.permissionVisible = true
              this.checkedKeys = res.data.checkedKeys.filter(function (val) { return checkedLists.indexOf(val) === -1 })
            }
            this.mdl = Object.assign({}, res.data)
            this.mdl.status = res.data.status.toString()
            this.visible = true
            this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.mdl, 'id', 'roleSort', 'roleCode', 'roleName', 'dataScope', 'status', 'remark'))
            })
          }).catch(res => {
            this.$message.error(((res.response || {}).data || {}).message || res.message)
          })
        }
      },
      onClose () {
        this.visible = false
        this.treeData = []
        this.checkedKeys = []
      },
      roleSubmit (e) {
        e.preventDefault()
        const checkedAll = this.treeCheck ? this.checkedKeys.concat(this.halfCheckedKeys) : this.checkedKeys.concat(Array.from(this.pidSet))
        if (this.permissionVisible && !checkedAll.length > 0) {
          this.$message.warning('请至少选择一个权限')
          return
        }
        this.form.validateFields((err, values) => {
          if (!err) {
            values.deptIds = this.permissionVisible ? checkedAll : []
            if (this.submitFlag === 'save') {
              addRole(values).then(res => {
                if (res.code === 200) {
                  this.$message.success('保存角色成功')
                  this.$emit('ok')
                  this.visible = false
                }
              }).catch(res => {
                this.$message.error(((res.response || {}).data || {}).message || res.message)
              })
            } else {
              editRole(values).then(res => {
                if (res.code === 200) {
                  this.$message.success('修改角色成功')
                  this.$emit('ok')
                  this.visible = false
                }
              }).catch(res => {
                this.$message.error(((res.response || {}).data || {}).message || res.message)
              })
            }
          }
        })
      }
    }
  }
</script>
